﻿using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.PlottingServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using ACAD = Autodesk.AutoCAD.ApplicationServices;
using System.Runtime.InteropServices;

namespace Plot08
{
	class LayoutTool
    {

        #region   用于Ucs至Wcs的坐标转换，使用的是objectarx 的函数 用的是混合编程技术，来自网络，注意Autocad2008 与Autodesk2013中acedTrans函数所在的文件位置不一样


#if CadVersion08

        [DllImport("acad.exe", CallingConvention = CallingConvention.Cdecl, EntryPoint = "acedTrans")]

#elif CadVersion13

        [DllImport("accore.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "acedTrans")]

#endif

        static extern int acedTrans(
          double[] point,
          IntPtr fromRb,
          IntPtr toRb,
          int disp,
          double[] result
        );

     #endregion

		#region 获取图纸空间的所有布局用到的方法

		/// <summary>
		/// 获取图纸空间的所有布局
		/// </summary>
		/// <param name="acDoc">当前文档</param>
		/// <returns>所有布局的集合List</returns>
		public static List<string> Get_Layouts(Document acDoc)
		{
			List<string> names_layout = new List<string>();

			// Get the current document and database

			Database acCurDb = acDoc.Database;

			// Get the layout dictionary of the current database
			using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) {
				DBDictionary lays = acTrans.GetObject(acCurDb.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary;

				acDoc.Editor.WriteMessage("\nLayouts:");

				// Step through and list each named layout and Model
				foreach (DBDictionaryEntry item in lays) {
					acDoc.Editor.WriteMessage("\n  " + item.Key);


					if (item.Key.Contains("Model") == false) {

						names_layout.Add(item.Key);
                        
					}

				}

				// Abort the changes to the database
				acTrans.Abort();
			}

			return names_layout;

		}

		#endregion

		#region 用到的选取图框块的方法

		/// <summary>
		/// 自动选择块名为block_Names之一的块到List
		/// </summary>
		/// <param name="block_Names">图框块名称List</param>
		/// <returns>得到的图框块的List，包括模型空间与图纸空间的所有给定名称的块</returns>
		static public List<BlockReference> Get_tk_BlocksAuto(List<string> block_Names)
		{
			Document doc = ACAD.Application.DocumentManager.MdiActiveDocument;

			Database db = doc.Database;

			Editor ed = doc.Editor;

			List<BlockReference> tks_block = new List<BlockReference>();

			List<string> names_view = new List<string>();


			int n = block_Names.Count() + 2;

			//			ACAD.Application.ShowAlertDialog(n.ToString());

			TypedValue[] acTypValAr = new TypedValue[n];

			acTypValAr.SetValue(new TypedValue((int)DxfCode.Operator, "<or"), 0);

			for (int i = 0; i < n - 2; i++) {

				acTypValAr.SetValue(new TypedValue((int)DxfCode.BlockName, block_Names[i]), i + 1);

				//				ACAD.Application.ShowAlertDialog(i.ToString());

			}

			acTypValAr.SetValue(new TypedValue((int)DxfCode.Operator, "or>"), n - 1);


			SelectionFilter filter = new SelectionFilter(acTypValAr);

			try {

				PromptSelectionResult res = ed.SelectAll(filter);

				if (res.Status != PromptStatus.OK) {

					//	ACAD.Application.ShowAlertDialog("出错了");

					return tks_block;
				}

				SelectionSet ss = res.Value;

				foreach (SelectedObject acSSObj in ss) {
					// 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned
					if (acSSObj != null) {
						using (Transaction acTrans = db.TransactionManager.StartTransaction()) {

							// 以写的方式打开选择的对象   Open the selected object for write

							Entity A_ent = acTrans.GetObject(acSSObj.ObjectId, OpenMode.ForWrite) as Entity;


							if (A_ent is BlockReference) {

								BlockReference block_tmp = A_ent as BlockReference;
                                
								if (block_tmp != null) {

                                    bool hasIn = false;

                                    hasIn = HasIn(tks_block, block_tmp);//如果图框块集中没有距离很近被认为是重合的图框，那么就把块添加到图框块集中

                                    if (hasIn == false)
                                    {
                                        tks_block.Add(block_tmp);
                                    }

								}

							}

						}
					}
				}

				return tks_block;


			} catch (System.Exception) {

				//				throw;

				return null;

			}


		}

        static public bool HasIn(List<BlockReference> tks_block, BlockReference blockObj)
        {
            bool hasIn = false;

            foreach (BlockReference block in tks_block)
            {
                Point3d minPt = blockObj.GeometricExtents.MinPoint;

                Point3d maxPT = blockObj.GeometricExtents.MaxPoint;

                double len = minPt.DistanceTo(maxPT) / 10.0;

                if (minPt.DistanceTo(block.GeometricExtents.MinPoint) < len)
                {
                    if (blockObj.OwnerId == block.OwnerId)
                    {

                        hasIn = true;
                        break;
                    }

                }

            }

            return hasIn;

        }

        static public void BlockOrionSize(BlockReference block, out double width, out double height)
        {
            width = 0;
            height = 0;

            double xScale = block.ScaleFactors.X;

            double w = block.GeometricExtents.MaxPoint.X - block.GeometricExtents.MinPoint.X;

            double h = block.GeometricExtents.MaxPoint.Y - block.GeometricExtents.MinPoint.Y;

            width = w * xScale;

            height = h * xScale;

        }

		
		/// <summary>
		/// 自动选择块名为block_Names之一的块到List
		/// </summary>
		/// <param name="block_Names">图框块名称List</param>
		/// <param name="_nmSpace">指定图框块所在的空间</param>
		/// <returns>得到的图框块的List</returns>
		static public List<BlockReference> Get_tk_BlocksAuto(List<string> block_Names, string _nmSpace)
		{
			Document doc = ACAD.Application.DocumentManager.MdiActiveDocument;

			Database db = doc.Database;

			Editor ed = doc.Editor;

			List<BlockReference> tks_block = new List<BlockReference>();

			List<string> names_view = new List<string>();


			int n = block_Names.Count() + 2;

			//			ACAD.Application.ShowAlertDialog(n.ToString());

			TypedValue[] acTypValAr = new TypedValue[n];

			acTypValAr.SetValue(new TypedValue((int)DxfCode.Operator, "<or"), 0);

			for (int i = 0; i < n - 2; i++) {

				acTypValAr.SetValue(new TypedValue((int)DxfCode.BlockName, block_Names[i]), i + 1);

				//				ACAD.Application.ShowAlertDialog(i.ToString());

			}

			acTypValAr.SetValue(new TypedValue((int)DxfCode.Operator, "or>"), n - 1);


			SelectionFilter filter = new SelectionFilter(acTypValAr);

			try {

				PromptSelectionResult res = ed.SelectAll(filter);

				if (res.Status != PromptStatus.OK) {

					//					ACAD.Application.ShowAlertDialog("出错了");

					return tks_block;
				}

				SelectionSet ss = res.Value;

				foreach (SelectedObject acSSObj in ss) {
					// 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned
					if (acSSObj != null) {
						using (Transaction acTrans = db.TransactionManager.StartTransaction()) {

							// 以写的方式打开选择的对象   Open the selected object for write

							Entity A_ent = acTrans.GetObject(acSSObj.ObjectId, OpenMode.ForRead) as Entity;


							if (A_ent is BlockReference) {

								BlockReference block_tmp = A_ent as BlockReference;
                                
								if (block_tmp != null) {
									
									
									if (_nmSpace.ToUpper().Contains("PAPER") && block_tmp.BlockName.ToUpper().Contains("PAPER")) {


                                        bool hasIn = false;

                                        hasIn = HasIn(tks_block, block_tmp);//如果图框块集中没有距离很近被认为是重合的图框，那么就把块添加到图框块集中

                                        if (hasIn == false)
                                        {
                                            tks_block.Add(block_tmp);
                                        }

                                        //tks_block.Add(block_tmp);

									}

									if (_nmSpace.ToUpper().Contains("MODEL") && block_tmp.BlockName.ToUpper().Contains("MODEL")) {


                                        bool hasIn = false;

                                        hasIn = HasIn(tks_block, block_tmp);//如果图框块集中没有距离很近被认为是重合的图框，那么就把块添加到图框块集中

                                        if (hasIn == false)
                                        {
                                            tks_block.Add(block_tmp);
                                        }

										
                                        //tks_block.Add(block_tmp);
					
									}

                                    if (_nmSpace.ToUpper().Contains("ALL"))
                                    {

                                        bool hasIn = false;

                                        hasIn = HasIn(tks_block, block_tmp);//如果图框块集中没有距离很近被认为是重合的图框，那么就把块添加到图框块集中

                                        if (hasIn == false)
                                        {
                                            tks_block.Add(block_tmp);
                                        }

                                        //tks_block.Add(block_tmp);

                                    }




								}

							}

						}
					}
				}

				return tks_block;


			} catch (System.Exception) {

				//				throw;

				return null;

			}


		}
		
		
		

		/// <summary>
		/// 手动选择给定名字List的图框块List
		/// </summary>
		/// <param name="block_Names">图框块名称List</param>
		/// <returns>得到的图框块的List，包括当前空间的所有给定名称块</returns>
		static public List<BlockReference> Get_tk_BlocksBySelect(List<string> block_Names)
		{

			Document doc = ACAD.Application.DocumentManager.MdiActiveDocument;

			Database db = doc.Database;

			Editor ed = doc.Editor;

			List<BlockReference> tks_block = new List<BlockReference>();

			int n = block_Names.Count() + 2;

			//			ACAD.Application.ShowAlertDialog(n.ToString());

			TypedValue[] acTypValAr = new TypedValue[n];

			acTypValAr.SetValue(new TypedValue((int)DxfCode.Operator, "<or"), 0);

			for (int i = 0; i < n - 2; i++) {

				acTypValAr.SetValue(new TypedValue((int)DxfCode.BlockName, block_Names[i]), i + 1);

				//				ACAD.Application.ShowAlertDialog(i.ToString());

			}

			acTypValAr.SetValue(new TypedValue((int)DxfCode.Operator, "or>"), n - 1);


			SelectionFilter filter = new SelectionFilter(acTypValAr);


			PromptSelectionOptions Opts = new PromptSelectionOptions();

			Opts.AllowDuplicates = false;

			Opts.RejectObjectsOnLockedLayers = true;

			Opts.MessageForAdding = "请选择要打印范围《包含图框的区域》";


			try {

				PromptSelectionResult res = ed.GetSelection(Opts, filter);

				if (res.Status != PromptStatus.OK) {
					return null;
				}

				SelectionSet ss = res.Value;

				foreach (SelectedObject acSSObj in ss) {
					// 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned
					if (acSSObj != null) {
						using (Transaction acTrans = db.TransactionManager.StartTransaction()) {

							// 以写的方式打开选择的对象   Open the selected object for write

							Entity A_ent = acTrans.GetObject(acSSObj.ObjectId, OpenMode.ForRead) as Entity;


							if (A_ent is BlockReference) {

								BlockReference block_tmp = A_ent as BlockReference;

								string name_tk = block_tmp.Name;
								//
								//							if (tk_names.Contains(block_name)) {


                                bool hasIn = false;

                                hasIn = HasIn(tks_block, block_tmp);//如果图框块集中没有距离很近被认为是重合的图框，那么就把块添加到图框块集中

                                if (hasIn == false)
                                {
                                    tks_block.Add(block_tmp);
                                }

                                //tks_block.Add(block_tmp);

								//							}

							}

						}
					}
				}

				return tks_block;


			} catch (System.Exception) {

				//				throw;

				return null;

			}


		}
		
		/// <summary>
		/// 自动选择给定块名集合的图块
		/// </summary>
		/// <param name="block_Names">图块名称的List</param>
		/// <returns>选择到的块的ObjectId集合包括模型空间与图纸空间的所有给定的</returns>
		static public List<ObjectId> Get_tk_BlocksIds(List<string> block_Names)
		{
			List<ObjectId> ids = new List<ObjectId>();

			ids.Clear();

			Document doc = ACAD.Application.DocumentManager.MdiActiveDocument;

			Database db = doc.Database;

			Editor ed = doc.Editor;

			List<BlockReference> tks_block = new List<BlockReference>();

			List<string> names_view = new List<string>();


			int n = block_Names.Count() + 2;

			//			ACAD.Application.ShowAlertDialog(n.ToString());

			TypedValue[] acTypValAr = new TypedValue[n];

			acTypValAr.SetValue(new TypedValue((int)DxfCode.Operator, "<or"), 0);

			for (int i = 0; i < n - 2; i++) {

				acTypValAr.SetValue(new TypedValue((int)DxfCode.BlockName, block_Names[i]), i + 1);

				//				ACAD.Application.ShowAlertDialog(i.ToString());

			}

			acTypValAr.SetValue(new TypedValue((int)DxfCode.Operator, "or>"), n - 1);


			SelectionFilter filter = new SelectionFilter(acTypValAr);

			try {

				PromptSelectionResult res = ed.SelectAll(filter);

				if (res.Status != PromptStatus.OK) {

					//					ACAD.Application.ShowAlertDialog("出错了");

					return null;
				}

				SelectionSet ss = res.Value;

				foreach (SelectedObject acSSObj in ss) {
					// 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned
					if (acSSObj != null) {
						using (Transaction acTrans = db.TransactionManager.StartTransaction()) {

							// 以写的方式打开选择的对象   Open the selected object for write

							Entity A_ent = acTrans.GetObject(acSSObj.ObjectId, OpenMode.ForRead) as Entity;


							if (A_ent is BlockReference) {
								
								ids.Add(acSSObj.ObjectId);

							}

						}
					}
				}

				return ids;


			} catch (System.Exception) {

				//				throw;

				return null;

			}


		}



		#endregion

		#region 没有用到的打印设置


		/// <summary>
		/// 根据给定的页面设置参数进行打印，目前没用用到。
		/// </summary>
		/// <param name="E2d">图框块所对应的Extend2d范围</param>
		/// <param name="outFname">打印到文件时的名称</param>
		/// <param name="plottor">打印机</param>
		/// <param name="plotsize">纸张尺寸</param>
		/// <param name="toFile">是否打印到文件</param>
		/// <param name="plotstyle">打印样式</param>
		/// <param name="blxs_ob">打印比例</param>
		/// <returns></returns>
		public static bool plotWindow(Extents2d E2d, string outFname, string plottor, string plotsize, bool toFile, string plotstyle, double blxs_ob)
		{
			bool flag;

			flag = false;

			Document mdiActiveDocument = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

			Database database = mdiActiveDocument.Database;

			using (Transaction transaction = database.TransactionManager.StartTransaction()) {
				LayoutManager current = LayoutManager.Current;
				Layout source = (Layout)transaction.GetObject(current.GetLayoutId(current.CurrentLayout), OpenMode.ForRead);
				PlotInfo info = new PlotInfo {
					Layout = source.ObjectId
				};
				PlotSettings plotSet = new PlotSettings(source.ModelType);

				plotSet.CopyFrom(source);

				PlotSettingsValidator validator2 = PlotSettingsValidator.Current;

				validator2.SetPlotConfigurationName(plotSet, plottor, plotsize);

				validator2.SetPlotWindowArea(plotSet, E2d);

				validator2.SetPlotType(plotSet, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);

				validator2.RefreshLists(plotSet);

				validator2.SetCurrentStyleSheet(plotSet, plotstyle);

				validator2.SetPlotCentered(plotSet, true);

				validator2.SetPlotOrigin(plotSet, new Point2d(0, 0));



				if (NeedRotate(E2d, plotsize)) {
					validator2.SetPlotRotation(plotSet, PlotRotation.Degrees090);
				} else {
					validator2.SetPlotRotation(plotSet, PlotRotation.Degrees000);
				}

				validator2.SetPlotPaperUnits(plotSet, PlotPaperUnit.Millimeters);



				if (blxs_ob == 0) {
					validator2.SetUseStandardScale(plotSet, true);

					validator2.SetStdScaleType(plotSet, StdScaleType.ScaleToFit);

				} else {

					validator2.SetUseStandardScale(plotSet, false);

					validator2.SetCustomPrintScale(plotSet, new CustomScale(1, blxs_ob));


				}

				validator2.SetPlotCentered(plotSet, true);

				info.OverrideSettings = plotSet;

				PlotConfig config = PlotConfigManager.CurrentConfig;

				//Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(config.PlotToFileCapability.ToString());

				if (config.PlotToFileCapability == PlotToFileCapability.MustPlotToFile) {
					toFile = true;

				} else {
					toFile = false;

				}

				new PlotInfoValidator { MediaMatchingPolicy = MatchingPolicy.MatchEnabled }.Validate(info);

				Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("BACKGROUNDPLOT", 0);

				while (Autodesk.AutoCAD.PlottingServices.PlotFactory.ProcessPlotState == ProcessPlotState.ForegroundPlotting) {
					Thread.Sleep(10);
				}
				if (Autodesk.AutoCAD.PlottingServices.PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting) {
					using (PlotEngine engine = Autodesk.AutoCAD.PlottingServices.PlotFactory.CreatePublishEngine()) {
						PlotProgressDialog plotProgress = new PlotProgressDialog(false, 1, true);

						using (plotProgress) {
							plotProgress.set_PlotMsgString(PlotMessageIndex.DialogTitle, "打印进度");

							plotProgress.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "取消打印");

							plotProgress.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "打印进度");

							plotProgress.LowerPlotProgressRange = 0;

							plotProgress.UpperPlotProgressRange = 100;

							plotProgress.PlotProgressPos = 0;

							plotProgress.OnBeginPlot();

							plotProgress.IsVisible = false;

							engine.BeginPlot(plotProgress, null);

							engine.BeginDocument(info, mdiActiveDocument.Name, null, 1, toFile, outFname);

							plotProgress.set_PlotMsgString(PlotMessageIndex.Status, "正在打印 " + mdiActiveDocument.Name + " - " + source.LayoutName);

							plotProgress.OnBeginSheet();

							plotProgress.LowerSheetProgressRange = 0;

							plotProgress.UpperSheetProgressRange = 100;

							plotProgress.SheetProgressPos = 0;

							PlotPageInfo pageInfo = new PlotPageInfo();

							engine.BeginPage(pageInfo, info, true, null);

							engine.BeginGenerateGraphics(null);

							engine.EndGenerateGraphics(null);

							engine.EndPage(null);

							plotProgress.SheetProgressPos = 100;

							plotProgress.OnEndSheet();

							engine.EndDocument(null);

							plotProgress.PlotProgressPos = 100;

							plotProgress.OnEndPlot();

							engine.EndPlot(null);
						}
					}
				}
			}

			return flag;
		}
		/// <summary>
		/// 根据打印设置，进行打印，目前没有用到
		/// </summary>
		/// <param name="E2d">图框块所对应的Extend2d范围</param>
		/// <param name="outFname">打印到文件时的名称</param>
		/// <param name="plSet">给定的打印设置</param>
		/// <returns>打印成功为真</returns>
		public static bool plotWindowByPlotSetOb(Extents2d E2d, string outFname, PlotSettings plSet)
		{
			bool flag;

			flag = false;

			Document mdiActiveDocument = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

			Database database = mdiActiveDocument.Database;

			using (Transaction transaction = database.TransactionManager.StartTransaction()) {

				LayoutManager current = LayoutManager.Current;

				Layout source = (Layout)transaction.GetObject(current.GetLayoutId(current.CurrentLayout), OpenMode.ForRead);

				PlotInfo info = new PlotInfo {
					Layout = source.ObjectId
				};
				PlotSettings plotSet = new PlotSettings(source.ModelType);

				plotSet.CopyFrom(source);

				PlotSettingsValidator validator2 = PlotSettingsValidator.Current;

				validator2.SetPlotConfigurationName(plotSet, plSet.PlotConfigurationName, plSet.CanonicalMediaName);

				validator2.SetPlotWindowArea(plotSet, E2d);

				validator2.SetPlotType(plotSet, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);

				validator2.RefreshLists(plotSet);

				validator2.SetCurrentStyleSheet(plotSet, plSet.CurrentStyleSheet);

				validator2.SetPlotCentered(plotSet, plSet.PlotCentered);

				validator2.SetPlotOrigin(plotSet, plSet.PlotOrigin);



				if (NeedRotate(E2d, plSet.CanonicalMediaName)) {
					validator2.SetPlotRotation(plotSet, PlotRotation.Degrees090);
				} else {
					validator2.SetPlotRotation(plotSet, PlotRotation.Degrees000);
				}

				validator2.SetPlotPaperUnits(plotSet, plSet.PlotPaperUnits);

				validator2.SetCustomPrintScale(plotSet, plSet.CustomPrintScale);



				validator2.SetPlotCentered(plotSet, true);

				info.OverrideSettings = plotSet;

				PlotConfig config = PlotConfigManager.CurrentConfig;

				//Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(config.PlotToFileCapability.ToString());

				//if (config.PlotToFileCapability == PlotToFileCapability.MustPlotToFile)
				//{
				//    toFile = true;

				//}
				//else
				//{
				//    toFile = false;

				//}

				new PlotInfoValidator { MediaMatchingPolicy = MatchingPolicy.MatchEnabled }.Validate(info);

				Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("BACKGROUNDPLOT", 0);

				while (Autodesk.AutoCAD.PlottingServices.PlotFactory.ProcessPlotState == ProcessPlotState.ForegroundPlotting) {
					Thread.Sleep(10);
				}
				if (Autodesk.AutoCAD.PlottingServices.PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting) {
					using (PlotEngine engine = Autodesk.AutoCAD.PlottingServices.PlotFactory.CreatePublishEngine()) {
						PlotProgressDialog plotProgress = new PlotProgressDialog(false, 1, true);

						using (plotProgress) {
							plotProgress.set_PlotMsgString(PlotMessageIndex.DialogTitle, "打印进度");

							plotProgress.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "取消打印");

							plotProgress.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "打印进度");

							plotProgress.LowerPlotProgressRange = 0;

							plotProgress.UpperPlotProgressRange = 100;

							plotProgress.PlotProgressPos = 0;

							plotProgress.OnBeginPlot();

							plotProgress.IsVisible = false;

							engine.BeginPlot(plotProgress, null);

							engine.BeginDocument(info, mdiActiveDocument.Name, null, 1, true, outFname);

							plotProgress.set_PlotMsgString(PlotMessageIndex.Status, "正在打印 " + mdiActiveDocument.Name + " - " + source.LayoutName);

							plotProgress.OnBeginSheet();

							plotProgress.LowerSheetProgressRange = 0;

							plotProgress.UpperSheetProgressRange = 100;

							plotProgress.SheetProgressPos = 0;

							PlotPageInfo pageInfo = new PlotPageInfo();

							engine.BeginPage(pageInfo, info, true, null);

							engine.BeginGenerateGraphics(null);

							engine.EndGenerateGraphics(null);

							engine.EndPage(null);

							plotProgress.SheetProgressPos = 100;

							plotProgress.OnEndSheet();

							engine.EndDocument(null);

							plotProgress.PlotProgressPos = 100;

							plotProgress.OnEndPlot();

							engine.EndPlot(null);
						}
					}
				}
			}

			return flag;
		}


		/// <summary>
		/// 根据当前布局（包括模型）中的当前页面设置，打印图框块范围，暂时没有用到
		/// </summary>
		/// <param name="E2d">图框块所对应的Extend2d范围</param>
		/// <param name="outFname">打印到文件时的名称</param>
		/// <param name="plotSetName">页面设置名称</param>
		/// <returns>打印成功为真</returns>
		public static bool plotWindowByPlotSetName(Extents2d E2d, string outFname, string plotSetName)
		{
			bool flag;

			flag = false;

			Document mdiActiveDocument = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

			Database database = mdiActiveDocument.Database;

			using (Transaction transaction = database.TransactionManager.StartTransaction()) {

				LayoutManager current = LayoutManager.Current;

				Layout source = (Layout)transaction.GetObject(current.GetLayoutId(current.CurrentLayout), OpenMode.ForRead);

				PlotInfo info = new PlotInfo {
					Layout = source.ObjectId
				};
				PlotSettings plotSet = new PlotSettings(source.ModelType);

				plotSet.CopyFrom(source);

				PlotSettingsValidator validator2 = PlotSettingsValidator.Current;

				//validator2.SetPlotConfigurationName(plotSet, plSet.PlotConfigurationName, plSet.CanonicalMediaName);

				validator2.SetPlotWindowArea(plotSet, E2d);

				validator2.SetPlotType(plotSet, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);

				validator2.RefreshLists(plotSet);

				//validator2.SetCurrentStyleSheet(plotSet, plSet.CurrentStyleSheet);

				//validator2.SetPlotCentered(plotSet, plSet.PlotCentered);

				//validator2.SetPlotOrigin(plotSet, plSet.PlotOrigin);



				if (NeedRotate(E2d, plotSet.CanonicalMediaName)) {
					validator2.SetPlotRotation(plotSet, PlotRotation.Degrees090);
				} else {
					validator2.SetPlotRotation(plotSet, PlotRotation.Degrees000);
				}

				//validator2.SetPlotPaperUnits(plotSet, plSet.PlotPaperUnits);

				//validator2.SetCustomPrintScale(plotSet, plSet.CustomPrintScale);

				validator2.SetPlotCentered(plotSet, true);

				info.OverrideSettings = plotSet;

				PlotConfig config = PlotConfigManager.CurrentConfig;

				//Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(config.PlotToFileCapability.ToString());

				bool toFile = false;

				if (config.PlotToFileCapability == PlotToFileCapability.MustPlotToFile) {
					toFile = true;

				} else {
					toFile = false;

				}

				new PlotInfoValidator { MediaMatchingPolicy = MatchingPolicy.MatchEnabled }.Validate(info);

				Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("BACKGROUNDPLOT", 0);

				while (Autodesk.AutoCAD.PlottingServices.PlotFactory.ProcessPlotState == ProcessPlotState.ForegroundPlotting) {
					Thread.Sleep(10);
				}
				if (Autodesk.AutoCAD.PlottingServices.PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting) {
					using (PlotEngine engine = Autodesk.AutoCAD.PlottingServices.PlotFactory.CreatePublishEngine()) {
						PlotProgressDialog plotProgress = new PlotProgressDialog(false, 1, true);

						using (plotProgress) {
							plotProgress.set_PlotMsgString(PlotMessageIndex.DialogTitle, "打印进度");

							plotProgress.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "取消打印");

							plotProgress.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "打印进度");

							plotProgress.LowerPlotProgressRange = 0;

							plotProgress.UpperPlotProgressRange = 100;

							plotProgress.PlotProgressPos = 0;

							plotProgress.OnBeginPlot();

							plotProgress.IsVisible = false;

							engine.BeginPlot(plotProgress, null);

							engine.BeginDocument(info, mdiActiveDocument.Name, null, 1, toFile, outFname);

							plotProgress.set_PlotMsgString(PlotMessageIndex.Status, "正在打印 " + mdiActiveDocument.Name + " - " + source.LayoutName);

							plotProgress.OnBeginSheet();

							plotProgress.LowerSheetProgressRange = 0;

							plotProgress.UpperSheetProgressRange = 100;

							plotProgress.SheetProgressPos = 0;

							PlotPageInfo pageInfo = new PlotPageInfo();

							engine.BeginPage(pageInfo, info, true, null);

							engine.BeginGenerateGraphics(null);

							engine.EndGenerateGraphics(null);

							engine.EndPage(null);

							plotProgress.SheetProgressPos = 100;

							plotProgress.OnEndSheet();

							engine.EndDocument(null);

							plotProgress.PlotProgressPos = 100;

							plotProgress.OnEndPlot();

							engine.EndPlot(null);
						}
					}
				}
			}

			return flag;
		}














		#endregion

		#region 用到的与打印直接相关的方法

     /*
        public static bool PlotWindowByCurPlotSetting(BlockReference tkBlock, string outFname)
        {
            Extents2d E2d = LayoutTool.GetBlockExtent2d(tkBlock);

            string tkName = tkBlock.Name;


            int width =Convert.ToInt32(E2d.MaxPoint.X - E2d.MinPoint.X);

            int height =Convert.ToInt32(E2d.MaxPoint.Y - E2d.MinPoint.Y);

            bool useScale = false;

            bool useFit = false;

            double CSxs = 1;

            double blxs = 1;

            bool flag;

            flag = false;

            Document mdiActiveDocument = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database database = mdiActiveDocument.Database;

            using (Transaction transaction = database.TransactionManager.StartTransaction())
            {

                LayoutManager current = LayoutManager.Current;

                Layout source = (Layout)transaction.GetObject(current.GetLayoutId(current.CurrentLayout), OpenMode.ForRead);

                PlotInfo info = new PlotInfo
                {
                    Layout = source.ObjectId
                };
                PlotSettings plotSet = new PlotSettings(source.ModelType);

                plotSet.CopyFrom(source);

                PlotSettingsValidator validator2 = PlotSettingsValidator.Current;

                validator2.RefreshLists(plotSet);

                //validator2.SetPlotConfigurationName(plotSet, plSet.PlotConfigurationName, plSet.CanonicalMediaName);

                validator2.SetPlotWindowArea(plotSet, E2d);

                validator2.SetPlotType(plotSet, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);

               
                double tkWidthStd = 420.0;


                if (tkName.ToUpper().Contains("A4"))
                {
                    tkWidthStd = 210;
                }
                if (tkName.ToUpper().Contains("A3"))
                {
                    tkWidthStd = 420.0;
                }

                if (tkName.ToUpper().Contains("A2"))
                {
                    tkWidthStd = 594.0;
                }
                if (tkName.ToUpper().Contains("A1"))
                {
                    tkWidthStd = 841.0;
                }
                if (tkName.ToUpper().Contains("A0"))
                {
                    tkWidthStd = 1189.0;
                }

                //double  paperWidth =plotSet.PlotPaperSize.X;

                blxs = width / tkWidthStd;


                if (blxs >= 1)
                {

                    useScale = true;

                    CSxs = blxs;

                }

                if (0.001 < blxs && blxs < 1)
                {

                    useScale = true;

                    CSxs = blxs;

                }


                if (blxs < 0.001)
                {

                    useFit = true;

                }

                if (useFit == true)
                {

                    validator2.SetUseStandardScale(plotSet, true);

                    validator2.SetStdScaleType(plotSet, StdScaleType.ScaleToFit);

                }


                if (useScale == true)
                {

                    validator2.SetUseStandardScale(plotSet, false);

                    validator2.SetCustomPrintScale(plotSet, new CustomScale(1, CSxs));

                }

                //validator2.SetPlotOrigin(plotSet, new Point2d(0, 0));

                //validator2.SetPlotCentered(plotSet, true);

                //validator2.SetCurrentStyleSheet(plotSet, plSet.CurrentStyleSheet);

                //validator2.SetPlotCentered(plotSet, plSet.PlotCentered);

                //validator2.SetPlotOrigin(plotSet, plSet.PlotOrigin);



                if (NeedRotate(E2d, plotSet.CanonicalMediaName))
                {
                    validator2.SetPlotRotation(plotSet, PlotRotation.Degrees090);
                }
                else
                {
                    validator2.SetPlotRotation(plotSet, PlotRotation.Degrees000);
                }

                //validator2.SetPlotPaperUnits(plotSet, plSet.PlotPaperUnits);

                //validator2.SetCustomPrintScale(plotSet, plSet.CustomPrintScale);

                validator2.SetPlotCentered(plotSet, true);

                info.OverrideSettings = plotSet;

                PlotConfig config = PlotConfigManager.CurrentConfig;

                //Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(config.PlotToFileCapability.ToString());

                bool toFile = false;

                if (config.PlotToFileCapability == PlotToFileCapability.MustPlotToFile)
                {
                    toFile = true;

                }
                else
                {
                    toFile = false;

                }

                //if (config.PlotToFileCapability == PlotToFileCapability.PlotToFileAllowed || config.PlotToFileCapability == PlotToFileCapability.MustPlotToFile)
                //{
                //    toFile = true;

                //}
                //else
                //{
                //    toFile = false;

                //}

                new PlotInfoValidator { MediaMatchingPolicy = MatchingPolicy.MatchEnabled }.Validate(info);

                Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("BACKGROUNDPLOT", 0);

                while (Autodesk.AutoCAD.PlottingServices.PlotFactory.ProcessPlotState == ProcessPlotState.ForegroundPlotting)
                {
                    Thread.Sleep(10);
                }
                if (Autodesk.AutoCAD.PlottingServices.PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
                {
                    using (PlotEngine engine = Autodesk.AutoCAD.PlottingServices.PlotFactory.CreatePublishEngine())
                    {
                        PlotProgressDialog plotProgress = new PlotProgressDialog(false, 1, true);

                        //PlotProgressDialog plotProgress = new PlotProgressDialog(false, 5, true);

                        using (plotProgress)
                        {
                            plotProgress.set_PlotMsgString(PlotMessageIndex.DialogTitle, "打印进度");

                            plotProgress.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "取消打印");

                            plotProgress.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "打印进度");

                            plotProgress.LowerPlotProgressRange = 0;

                            plotProgress.UpperPlotProgressRange = 100;

                            plotProgress.PlotProgressPos = 0;

                            plotProgress.OnBeginPlot();

                            plotProgress.IsVisible = false;

                            //plotProgress.IsVisible = true;

                            engine.BeginPlot(plotProgress, null);

                            engine.BeginDocument(info, mdiActiveDocument.Name, null, 1, toFile, outFname);

                            plotProgress.set_PlotMsgString(PlotMessageIndex.Status, "正在打印 " + mdiActiveDocument.Name + " - " + source.LayoutName);

                            plotProgress.OnBeginSheet();

                            plotProgress.LowerSheetProgressRange = 0;

                            plotProgress.UpperSheetProgressRange = 100;

                            plotProgress.SheetProgressPos = 0;

                            PlotPageInfo pageInfo = new PlotPageInfo();

                            engine.BeginPage(pageInfo, info, true, null);

                            engine.BeginGenerateGraphics(null);

                            engine.EndGenerateGraphics(null);

                            engine.EndPage(null);

                            plotProgress.SheetProgressPos = 100;

                            plotProgress.OnEndSheet();

                            engine.EndDocument(null);

                            plotProgress.PlotProgressPos = 100;

                            plotProgress.OnEndPlot();

                            engine.EndPlot(null);
                        }
                    }
                }
            }

            return flag;
        }

        */



        public static bool PlotWindowByCurPlotSetting(BlockReference tkBlock, string outFname)
        {
            Extents2d E2d = LayoutTool.GetBlockExtent2d(tkBlock);

            string tkName = tkBlock.Name;

            int width = Convert.ToInt32(E2d.MaxPoint.X - E2d.MinPoint.X);

            int height = Convert.ToInt32(E2d.MaxPoint.Y - E2d.MinPoint.Y);

            bool useScale = false;

            bool useFit = false;

            double CSxs = 1;

            double blxs = 1;

            bool flag;

            flag = false;

            Document mdiActiveDocument = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database database = mdiActiveDocument.Database;

            using (Transaction transaction = database.TransactionManager.StartTransaction())
            {

                LayoutManager current = LayoutManager.Current;

                Layout source = (Layout)transaction.GetObject(current.GetLayoutId(current.CurrentLayout), OpenMode.ForRead);

                PlotInfo info = new PlotInfo
                {
                    Layout = source.ObjectId
                };
                PlotSettings plotSet = new PlotSettings(source.ModelType);

                plotSet.CopyFrom(source);

                PlotSettingsValidator validator2 = PlotSettingsValidator.Current;

                validator2.RefreshLists(plotSet);

                //validator2.SetPlotConfigurationName(plotSet, plSet.PlotConfigurationName, plSet.CanonicalMediaName);

                validator2.SetPlotWindowArea(plotSet, E2d);

                validator2.SetPlotType(plotSet, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);

                //double sizeWidth =Convert.ToInt32( plotSet.PlotPaperSize.X);

                //double tkWidthStd = sizeWidth;

                double tkWidthStd = 420.0;

                if (tkName.ToUpper().Contains("A4"))
                {
                    tkWidthStd = 297;
                }
                if (tkName.ToUpper().Contains("A3"))
                {
                    tkWidthStd = 420.0;
                }

                if (tkName.ToUpper().Contains("A2"))
                {
                    tkWidthStd = 594.0;
                }
                if (tkName.ToUpper().Contains("A1"))
                {
                    tkWidthStd = 841.0;
                }
                if (tkName.ToUpper().Contains("A0"))
                {
                    tkWidthStd = 1189.0;
                }

                blxs = width / tkWidthStd;


                if (blxs >= 1)
                {

                    useScale = true;

                    CSxs = blxs;

                }

                if (0.001 < blxs && blxs < 1)
                {

                    useScale = true;

                    CSxs = blxs;

                }


                if (blxs < 0.001)
                {

                    useFit = true;

                }

                if (useFit == true)
                {

                    validator2.SetUseStandardScale(plotSet, true);

                    validator2.SetStdScaleType(plotSet, StdScaleType.ScaleToFit);

                }


                if (useScale == true)
                {

                    validator2.SetUseStandardScale(plotSet, false);

                    validator2.SetCustomPrintScale(plotSet, new CustomScale(1, CSxs));

                }




                //validator2.SetPlotOrigin(plotSet, new Point2d(0, 0));

                //validator2.SetPlotCentered(plotSet, true);

                //validator2.SetCurrentStyleSheet(plotSet, plSet.CurrentStyleSheet);

                //validator2.SetPlotCentered(plotSet, plSet.PlotCentered);

                //validator2.SetPlotOrigin(plotSet, plSet.PlotOrigin);



                if (NeedRotate(E2d, plotSet.CanonicalMediaName))
                {
                    validator2.SetPlotRotation(plotSet, PlotRotation.Degrees090);
                }
                else
                {
                    validator2.SetPlotRotation(plotSet, PlotRotation.Degrees000);
                }

                //validator2.SetPlotPaperUnits(plotSet, plSet.PlotPaperUnits);

                //validator2.SetCustomPrintScale(plotSet, plSet.CustomPrintScale);

                validator2.SetPlotCentered(plotSet, true);

                info.OverrideSettings = plotSet;

                PlotConfig config = PlotConfigManager.CurrentConfig;

                //Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(config.PlotToFileCapability.ToString());

                bool toFile = false;

                if (config.PlotToFileCapability == PlotToFileCapability.MustPlotToFile)
                {
                    toFile = true;

                }
                else
                {
                    toFile = false;

                }

                //if (config.PlotToFileCapability == PlotToFileCapability.PlotToFileAllowed || config.PlotToFileCapability == PlotToFileCapability.MustPlotToFile)
                //{
                //    toFile = true;

                //}
                //else
                //{
                //    toFile = false;

                //}

                new PlotInfoValidator { MediaMatchingPolicy = MatchingPolicy.MatchEnabled }.Validate(info);

                Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("BACKGROUNDPLOT", 0);

                while (Autodesk.AutoCAD.PlottingServices.PlotFactory.ProcessPlotState == ProcessPlotState.ForegroundPlotting)
                {
                    Thread.Sleep(10);
                }
                if (Autodesk.AutoCAD.PlottingServices.PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
                {
                    using (PlotEngine engine = Autodesk.AutoCAD.PlottingServices.PlotFactory.CreatePublishEngine())
                    {
                        PlotProgressDialog plotProgress = new PlotProgressDialog(false, 1, true);

                        //PlotProgressDialog plotProgress = new PlotProgressDialog(false, 5, true);

                        using (plotProgress)
                        {
                            plotProgress.set_PlotMsgString(PlotMessageIndex.DialogTitle, "打印进度");

                            plotProgress.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "取消打印");

                            plotProgress.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "打印进度");

                            plotProgress.LowerPlotProgressRange = 0;

                            plotProgress.UpperPlotProgressRange = 100;

                            plotProgress.PlotProgressPos = 0;

                            plotProgress.OnBeginPlot();

                            plotProgress.IsVisible = false;

                            //plotProgress.IsVisible = true;

                            engine.BeginPlot(plotProgress, null);

                            engine.BeginDocument(info, mdiActiveDocument.Name, null, 1, toFile, outFname);

                            plotProgress.set_PlotMsgString(PlotMessageIndex.Status, "正在打印 " + mdiActiveDocument.Name + " - " + source.LayoutName);

                            plotProgress.OnBeginSheet();

                            plotProgress.LowerSheetProgressRange = 0;

                            plotProgress.UpperSheetProgressRange = 100;

                            plotProgress.SheetProgressPos = 0;

                            PlotPageInfo pageInfo = new PlotPageInfo();

                            engine.BeginPage(pageInfo, info, true, null);

                            engine.BeginGenerateGraphics(null);

                            engine.EndGenerateGraphics(null);

                            engine.EndPage(null);

                            plotProgress.SheetProgressPos = 100;

                            plotProgress.OnEndSheet();

                            engine.EndDocument(null);

                            plotProgress.PlotProgressPos = 100;

                            plotProgress.OnEndPlot();

                            engine.EndPlot(null);
                        }
                    }
                }
            }

            return flag;
        }












        #region 打印用到的基本方法，包括确定是否需要旋转打印范围，包括E2d的获取（坐标转换）

        /// <summary>
        /// 判断图框块与页面的匹配关系，判断是否需要旋转plotsize
        /// </summary>
        /// <param name="E2d">给定的Extend2d</param>
        /// <param name="plotsize">给定的纸张</param>
        /// <returns>需要旋转时为真</returns>
        public static bool NeedRotate(Extents2d E2d, string plotsize)
        {
            bool flag = false;
            MediaBounds mediaBounds = PlotConfigManager.CurrentConfig.GetMediaBounds(plotsize);
            Point2d lowerLeftPrintableArea = mediaBounds.LowerLeftPrintableArea;
            Point2d upperRightPrintableArea = mediaBounds.UpperRightPrintableArea;
            double num4 = Math.Abs((double)(upperRightPrintableArea.X - lowerLeftPrintableArea.X));
            double num = Math.Abs((double)(upperRightPrintableArea.Y - lowerLeftPrintableArea.Y));
            double num3 = Math.Abs((double)(E2d.MaxPoint.X - E2d.MinPoint.X));
            double num2 = Math.Abs((double)(E2d.MaxPoint.Y - E2d.MinPoint.Y));
            if (((num4 > num) & (num3 < num2)) | ((num4 < num) & (num3 > num2)))
            {
                flag = true;
            }
            return flag;
        }

        /// <summary>
        /// 获取图框块的Extends2d,注意这里需要进行一次坐标系的转换。
        /// </summary>
        /// <param name="blockReference">给定的图框块</param>
        /// <returns>Extends2d用于指定打印范围</returns>
        public static Extents2d GetBlockExtent2d(BlockReference blockReference)
        {

            Extents3d E3d = blockReference.GeometricExtents;

            Extents2d E2d = Ucs2Dcs(E3d.MinPoint, E3d.MaxPoint);

            return E2d;

            //return new Extents2d(new Point2d(E3d.MinPoint.X, E3d.MinPoint.Y), new Point2d(E3d.MaxPoint.X, E3d.MaxPoint.Y));

        }


        /// <summary>
        /// 对两个点进行坐标转换，生成打印需使用的E2d，这里进行了坐标系的转换
        /// </summary>
        /// <param name="objStart"></param>
        /// <param name="objEnd"></param>
        /// <returns></returns>
        public static Extents2d Ucs2Dcs(Point3d objStart, Point3d objEnd)
        {
            ResultBuffer rbFrom = new ResultBuffer(new TypedValue(5003, 1));

            ResultBuffer rbTo = new ResultBuffer(new TypedValue(5003, 2));

            double[] firres = new double[] { 0, 0, 0 };

            double[] secres = new double[] { 0, 0, 0 };


            acedTrans(
                objStart.ToArray(),
                rbFrom.UnmanagedObject,
                rbTo.UnmanagedObject,
                0,
                firres
            );


            acedTrans(
                objEnd.ToArray(),
                rbFrom.UnmanagedObject,
                rbTo.UnmanagedObject,
                0,
                secres
            );


            Extents2d window =
              new Extents2d(
                firres[0],
                firres[1],
                secres[0],
                secres[1]
              );
            return window;
        }


        /// <summary>
        /// 使用得到得块的E3d，生成打印需使用的E2d，这里进行了坐标系的转换
        /// </summary>
        /// <param name="e3d"></param>
        /// <returns></returns>
        public static Extents2d Ucs2Dcs(Extents3d e3d)
        {

            Point3d objStart = e3d.MinPoint;

            Point3d objEnd = e3d.MaxPoint;


            ResultBuffer rbFrom = new ResultBuffer(new TypedValue(5003, 1));

            ResultBuffer rbTo = new ResultBuffer(new TypedValue(5003, 2));


            double[] firres = new double[] { 0, 0, 0 };

            double[] secres = new double[] { 0, 0, 0 };


            acedTrans(
                objStart.ToArray(),
                rbFrom.UnmanagedObject,
                rbTo.UnmanagedObject,
                0,
                firres
            );


            acedTrans(
                objEnd.ToArray(),
                rbFrom.UnmanagedObject,
                rbTo.UnmanagedObject,
                0,
                secres
            );


            Extents2d window =
              new Extents2d(
                firres[0],
                firres[1],
                secres[0],
                secres[1]
              );
            return window;
        }



        #endregion


        #region 与页面设置相关的方法
      

        /// <summary>
		/// 判断当前布局（包括模型空间）是否有当前的页面设置
		/// </summary>
		/// <param name="acDoc">当前文档</param>
		/// <param name="plotSettingName">结果为真时，用于输出的页面设置名称</param>
		/// <returns></returns>
		public static bool HasPlotSeting(Document acDoc, out string plotSettingName)
		{
			bool has = false;

			plotSettingName = string.Empty;

			Database acCurDb = acDoc.Database;

			using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) {

				LayoutManager acLayoutMgr;

				acLayoutMgr = LayoutManager.Current;

				Layout acLayout = acTrans.GetObject(acLayoutMgr.GetLayoutId(acLayoutMgr.CurrentLayout), OpenMode.ForRead) as Layout;

				if (acLayout.PlotSettingsName != string.Empty && acLayout.PlotSettingsName.Length > 0) {
					if (acLayout.PlotConfigurationName != string.Empty && acLayout.CanonicalMediaName != string.Empty) {
						has = true;

						plotSettingName = acLayout.PlotSettingsName;

						if (acLayout.CurrentStyleSheet == string.Empty) {
							acDoc.Editor.WriteMessage("!!!!*****注意当前打印样式名为空");
                            
						}

						acDoc.Editor.WriteMessage("{0}为当前的页面设置,打印设备为{1}图纸尺寸为{2}，打印样式为{3}", acLayout.PlotSettingsName, acLayout.PlotConfigurationName, acLayout.CanonicalMediaName, acLayout.CurrentStyleSheet);

					}
				} else {
					has = false;
				}

				acTrans.Abort();
			}

			return has;

		}

        ///// <summary>
        ///// 将布局与页面设置关联起来
        ///// </summary>
        ///// <param name="layout_id">布局的ID</param>
        ///// <param name="pageSetup_name">页面设置名称</param>
        //public static bool AssignPage_SetupToLayout(ObjectId layout_id, string pageSetup_name)
        //{

        //    bool b = false;

        //    // Get the current document and database, and start a transaction
        //    Document acDoc = Application.DocumentManager.MdiActiveDocument;
        //    Database acCurDb = acDoc.Database;

        //    using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
        //    {
        //        // Reference the Layout Manager
        //        LayoutManager acLayoutMgr = LayoutManager.Current;

        //        // Get the current layout and output its name in the Command Line window

        //        Layout acLayout = acTrans.GetObject(layout_id, OpenMode.ForRead) as Layout;


        //        //if (acLayout.TabSelected == false)
        //        //{

        //        //    acLayoutMgr.CurrentLayout = acLayout.LayoutName;

        //        //}

        //        DBDictionary acPlSet = acTrans.GetObject(acCurDb.PlotSettingsDictionaryId, OpenMode.ForRead) as DBDictionary;

        //        try
        //        {
        //            // Check to see if the page setup exists
        //            if (acPlSet.Contains(pageSetup_name) == true)
        //            {

        //                PlotSettings plSet = acPlSet.GetAt(pageSetup_name).GetObject(OpenMode.ForRead) as PlotSettings;

        //                // Update the layout
        //                acLayout.UpgradeOpen();

                        

        //                acLayout.CopyFrom(plSet);

        //                // Save the new objects to the database
        //                acTrans.Commit();

        //                b = true;

        //            }
        //            else
        //            {
        //                PlotSettings plSet = new PlotSettings(acLayout.ModelType);





        //                // Ignore the changes made
        //                acTrans.Abort();
        //            }
        //        }
        //        catch (Exception)
        //        {

        //            b=false;
        //        }


        //    }

        //    return b;

        //}

        /// <summary>
        /// 将布局与页面设置关联起来
        /// </summary>
        /// <param name="layout_id">布局的ID</param>
        /// <param name="pageSetup_name">页面设置名称</param>
        public static bool AssignPage_SetupToLayout(ObjectId layout_id, string pageSetup_name)
        {

            bool b = false;

            // Get the current document and database, and start a transaction
            Document acDoc = Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // Reference the Layout Manager
                LayoutManager acLayoutMgr = LayoutManager.Current;

                // Get the current layout and output its name in the Command Line window

                Layout acLayout = acTrans.GetObject(layout_id, OpenMode.ForRead) as Layout;


                //if (acLayout.TabSelected == false)
                //{

                //    acLayoutMgr.CurrentLayout = acLayout.LayoutName;

                //}

                DBDictionary acPlSet = acTrans.GetObject(acCurDb.PlotSettingsDictionaryId, OpenMode.ForRead) as DBDictionary;

                try
                {
                    // Check to see if the page setup exists
                    if (acPlSet.Contains(pageSetup_name) == true)
                    {

                        PlotSettings plSet = acPlSet.GetAt(pageSetup_name).GetObject(OpenMode.ForRead) as PlotSettings;

                        // Update the layout
                        acLayout.UpgradeOpen();



                        acLayout.CopyFrom(plSet);

                        // Save the new objects to the database
                        acTrans.Commit();

                        b = true;

                    }
                    else
                    {

                        // Ignore the changes made
                        acTrans.Abort();
                    }
                }
                catch (Exception)
                {

                    b = false;
                }


            }

            return b;

        }






		/// <summary>
		/// 返回当前空间的BlockTableRecordId
		/// </summary>
		/// <param name="isModel">同时输出是否为模型空间，为真时是模型空间否则为图纸空间</param>
		/// <returns></returns>
		public static ObjectId GetCurSpaceObjectId(out bool isModel)
		{
			isModel = true;

			Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

			Database acDb = acDoc.Database;

			Editor acEd = acDoc.Editor;

			ObjectId _LayoutId = ObjectId.Null;

			using (Transaction acTrans = acDb.TransactionManager.StartTransaction()) {

				//获取模型空间的BlockTableId
				BlockTable acBlkTbl;

				acBlkTbl = acTrans.GetObject(acDb.BlockTableId, OpenMode.ForRead) as BlockTable;

				ObjectId tmpBtrId = acBlkTbl[BlockTableRecord.ModelSpace];

				LayoutManager current = LayoutManager.Current;

				//当前布局名字
				//current.CurrentLayout

				_LayoutId = current.GetLayoutId(current.CurrentLayout);

				Layout curLayout = acTrans.GetObject(_LayoutId, OpenMode.ForRead) as Layout;

				ObjectId btrID = curLayout.BlockTableRecordId;

				if (btrID == tmpBtrId) {

					isModel = true;

					acEd.WriteMessage("\n当前空间为模型空间\n");
				} else {
					isModel = false;

					acEd.WriteMessage("\n当前空间为图纸空间\n");
				}

				acTrans.Abort();
			}

			return _LayoutId;
		}



		/// <summary>
		/// 获取指定文档内的既有打印设置名称
		/// </summary>
		/// <param name="dwgFilepath">指定的文档</param>
		/// <param name="isModel">是否是模型空间，返回与isModel对应的打印设置信息</param>
		/// <param name="plotInfos">输出获取的打印样式基本信息</param>
		/// <returns>返回打印设置名称的list</returns>
		internal static List<string> GetPlotSetingsNames(string dwgFilepath, bool isModel, out List<string> plotInfos)
		{
			List<string> tmpNames = new List<string>();

			plotInfos = new List<string>();

			using (Database tmpDb = new Database(false, true)) {

				tmpDb.ReadDwgFile(dwgFilepath, System.IO.FileShare.Read, true, null);

				using (Transaction tmpTrans = tmpDb.TransactionManager.StartTransaction()) {

					DBDictionary tmpDict = tmpTrans.GetObject(tmpDb.PlotSettingsDictionaryId, OpenMode.ForRead) as DBDictionary;

					int i = 0;
					// List each named page setup
					foreach (DBDictionaryEntry item in tmpDict) {

						ObjectId settingsId = item.Value;

						PlotSettings settings = tmpTrans.GetObject(settingsId, OpenMode.ForRead) as PlotSettings;

						if (settings.ModelType == isModel) {

							if (item.Key != string.Empty) {

								tmpNames.Add(item.Key);

								string devName = settings.PlotConfigurationName;

								string medName = settings.CanonicalMediaName;

								string sheeetStyleName = settings.CurrentStyleSheet;

								string tmpStr = string.Format("<{0}>-名称为<{1}>的页面设置-devName: {2} -Paper: {3} sheetStyle: {4} ", (i + 1), item.Key, devName, medName, sheeetStyleName);

								plotInfos.Add(tmpStr);

								i++;

							}
						}

					}

					tmpTrans.Abort();

				}

			}

			return tmpNames;

		}






		/// <summary>
		/// 模型空间与图纸空间均导入指定的页面布局
		/// </summary>
		/// <param name="dwgFilePath">记录页面设置的dwg文件路径</param>
		/// <param name="aPlotSetingsName">用于导入的页面设置名称</param>
		/// <param name="_isModel">用于输入当前的布局类型，ture表示模型空间，false为图纸空间</param>
		/// <returns>如果导入成功返回值为真</returns>
		public static bool GetInAtPlotSetings(string dwgFilePath, string aPlotSetingsName, bool _isModel)
		{
			bool flag = false;

			Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

			Database acDb = acDoc.Database;

			Editor acEd = acDoc.Editor;

			if (System.IO.File.Exists(dwgFilePath)) {

				using (Database tmpDb = new Database(false, true)) {
					tmpDb.ReadDwgFile(dwgFilePath, System.IO.FileShare.Read, true, null);

					using (Transaction tmpTrans = tmpDb.TransactionManager.StartTransaction()) {
						//当前
						using (Transaction curTrans = acDb.TransactionManager.StartTransaction()) {
							//从目标db里面查找
							DBDictionary dbDict = tmpTrans.GetObject(tmpDb.PlotSettingsDictionaryId, OpenMode.ForRead) as DBDictionary;

							if (dbDict != null) {

								ObjectId settingsId = ObjectId.Null;

								settingsId = dbDict.GetAt(aPlotSetingsName);

								if (settingsId != null) {

									PlotSettings settings = null;

									settings = tmpTrans.GetObject(settingsId, OpenMode.ForRead) as PlotSettings;

									if (settings.ModelType == _isModel) {

										PlotSettings newSettingsModle = new PlotSettings(settings.ModelType);

										newSettingsModle.CopyFrom(settings);

										newSettingsModle.AddToPlotSettingsDictionary(acDb);

										curTrans.AddNewlyCreatedDBObject(newSettingsModle, true);

										flag = true;
									} else {
										flag = false;
									}
								} else {
									flag = false;
								}

							}

							curTrans.Commit();

						}

						tmpTrans.Commit();

					}

				}


			}

			return flag;

		}


        /// <summary>
        /// 模型空间与图纸空间均导入指定的页面布局
        /// </summary>
        /// <param name="dwgFilePath">记录页面设置的dwg文件路径</param>
        /// <param name="aPlotSetingsName">用于导入的页面设置名称</param>
        /// <param name="_isModel">用于输入当前的布局类型，ture表示模型空间，false为图纸空间</param>
        /// <returns>如果导入成功返回值为真</returns>
        public static bool GetInAtPlotSetings(string dwgFilePath, string aPlotSetingsName)
        {
            bool _isModel = true;

            bool flag = false;

            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database acDb = acDoc.Database;

            Editor acEd = acDoc.Editor;

            if (System.IO.File.Exists(dwgFilePath))
            {

                using (Database tmpDb = new Database(false, true))
                {
                    tmpDb.ReadDwgFile(dwgFilePath, System.IO.FileShare.Read, true, null);

                    using (Transaction tmpTrans = tmpDb.TransactionManager.StartTransaction())
                    {
                        //当前
                        using (Transaction curTrans = acDb.TransactionManager.StartTransaction())
                        {
                            //从目标db里面查找
                            DBDictionary dbDict = tmpTrans.GetObject(tmpDb.PlotSettingsDictionaryId, OpenMode.ForRead) as DBDictionary;

                            if (dbDict != null)
                            {

                                ObjectId settingsId = ObjectId.Null;

                                settingsId = dbDict.GetAt(aPlotSetingsName);

                                if (settingsId != null)
                                {

                                    PlotSettings settings = null;

                                    settings = tmpTrans.GetObject(settingsId, OpenMode.ForRead) as PlotSettings;

                                    if (settings.ModelType == _isModel)
                                    {

                                        PlotSettings newSettingsModle = new PlotSettings(settings.ModelType);

                                        newSettingsModle.CopyFrom(settings);

                                        newSettingsModle.AddToPlotSettingsDictionary(acDb);

                                        curTrans.AddNewlyCreatedDBObject(newSettingsModle, true);

                                        flag = true;
                                    }
                                    else
                                    {
                                        flag = false;
                                    }
                                }
                                else
                                {
                                    flag = false;
                                }

                            }

                            curTrans.Commit();

                        }

                        tmpTrans.Commit();

                    }

                }


            }

            return flag;

        }









        
		/// <summary>
		/// 获取指定名称的页面设置信息，并输出到相应的变量
		/// </summary>
		/// <param name="aPlotSetingsName">给定的页面设置名称</param>
		/// <param name="devName">打印设备名称</param>
		/// <param name="medName">媒体名称</param>
		/// <param name="sheeetStyleName">打印样式表</param>
		/// <returns></returns>
		internal static bool GetNamedPlotSetingsInfo(string aPlotSetingsName, out string devName, out string medName, out string sheeetStyleName)
		{
			bool flag = false;

			Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

			Database acDb = acDoc.Database;

			Editor acEd = acDoc.Editor;

			using (Transaction curTrans = acDb.TransactionManager.StartTransaction()) {
				//从目标db里面查找
				DBDictionary dbDict = curTrans.GetObject(acDb.PlotSettingsDictionaryId, OpenMode.ForRead) as DBDictionary;

				if (dbDict != null) {

					ObjectId settingsId = ObjectId.Null;

					settingsId = dbDict.GetAt(aPlotSetingsName);

					if (settingsId != null) {

						PlotSettings settings = null;

						settings = curTrans.GetObject(settingsId, OpenMode.ForRead) as PlotSettings;

						if (settings != null) {
							devName = settings.PlotConfigurationName;

							medName = settings.CanonicalMediaName;

							sheeetStyleName = settings.CurrentStyleSheet;

							flag = true;

							return flag;

						}
					}
				}

				curTrans.Abort();
			}

			devName = string.Empty;

			medName = string.Empty;

			sheeetStyleName = string.Empty;

			return flag;
        }


		#endregion






        #endregion

    }
}
